/**
 * 
 */
package arisufascion.com.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import arisufascion.com.R;
import arisufascion.com.activity.Activity_Detail;
import arisufascion.com.constant.Constants;
import arisufascion.com.db.ProductDataSource;
import arisufascion.com.model.Product;
import arisufascion.com.tabs.BadgeTabManager;
import arisufascion.com.tabs.TabGroupActivity;

import com.androidquery.AQuery;

/**
 * @author Kelvin
 * 
 */
public class ListNewProductAdapter extends BaseAdapter {
	Activity mContext;
	// public static final int ACTIVITY_CREATE = 10;
	private List<Product> products = new ArrayList<Product>();
	private AQuery aq;
	private Product product;
	private ProductDataSource database;

	public ListNewProductAdapter(Activity c, List<Product> products) {
		mContext = c;
		this.products = products;
		aq = new AQuery(c);
		database = new ProductDataSource(c);

	}

	@Override
	public int getCount() {
		int size = (products != null) ? products.size() : 0;
		return size;
	}

	@Override
	public Object getItem(int position) {
		Product item = (products != null) ? products.get(position) : null;
		return item;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public void addItem(List<Product> items) {
		int size = items.size();
		for (int i = 0; i < size; i++) {
			Product item = items.get(i);
			products.add(item);
		}
		this.notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder;
		product = products.get(position);

		LayoutInflater inflator = mContext.getLayoutInflater();
		if (convertView == null) {
			holder = new ViewHolder();

			convertView = inflator.inflate(R.layout.row_new_product, null);

			holder.txt_pro_name = (TextView) convertView
					.findViewById(R.id.txt_pro_name);

			holder.txt_pro_description = (TextView) convertView
					.findViewById(R.id.txt_pro_description);

			holder.txt_price = (TextView) convertView
					.findViewById(R.id.txt_price);

			holder.iv_product = (ImageView) convertView
					.findViewById(R.id.iv_product);

			holder.btn_add_tocart = (ImageButton) convertView
					.findViewById(R.id.btn_add_tocart);

			holder.progressBar = (ProgressBar) convertView
					.findViewById(R.id.progressBar);

			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.txt_pro_name.setText(product.getProduct_name());

		holder.txt_pro_description.setText(Html.fromHtml(product
				.getProduct_s_desc()));

		holder.txt_price.setText(String.valueOf(product.getProduct_price()));

		try {
			String url = String.format(Constants.SERVER_URL_IMAGES,
					String.valueOf(product.getImages().get(0).getFile_url()));

			Log.d("Kelvin:", url);

			aq.id(holder.iv_product).progress(holder.progressBar)
					.image(url, true, true, 0, R.drawable.icon_logo);

		} catch (Exception e) {
			// TODO: handle exception
		}
		
		holder.btn_add_tocart.setTag(product);
		
		holder.btn_add_tocart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Product pr=(Product)v.getTag();

				if (pr.getAttribute().size() > 0) {

					Bundle bundle = new Bundle();
					bundle.putParcelable("product", pr);
					Intent intent_product = new Intent(mContext,
							Activity_Detail.class);

					intent_product.putExtras(bundle);
					
					TabGroupActivity tabGroupActivity = (TabGroupActivity) mContext.getParent();
					tabGroupActivity.startChildActivity("Activity_Detail",
							intent_product);
					
				} else {
					database.open();
					
					Product pro = database.getProductById(pr
							.getVirtuemart_product_id());
					
					if (pro.getVirtuemart_product_id() == null) {
						
						database.InsertdatatoTable(
								Integer.parseInt(pr.getVirtuemart_product_id()),
								pr.getProduct_name(),
								pr.getProduct_desc(),
								pr.getProduct_s_desc(),
								pr.getProduct_price(),pr.getColor_id(),pr.getQuantity(), pr.getColor_image(), 1,pr.getColor_size());
						
						// insert array images of product on database local
						for (int i = 0; i < pr.getImages().size(); i++) {
							database.createImagesProduct(pr.getImages()
									.get(i).getFile_url(), Integer
									.parseInt(pr
											.getVirtuemart_product_id()));
						}
						
					}else{
						if(pr.getQuantity()>=pro.getQuantity()+1){
							pro.setQuantity(pro.getQuantity()+1);
							database.updateProduct(pro);
						}else{
							Toast.makeText(mContext, 	Html.fromHtml("<font color='red'>Max quantity reached, new quantity set to "
									+ pr.getQuantity()
							+ "</font>"), Toast.LENGTH_SHORT).show();
						
						}
						
					}
					int index=0 ;
					
					for (int i = 0; i < database.getProducts().size(); i++) {
						index+=database.getProducts().get(i).getQuantity();
					}
					 BadgeTabManager.getInstance().setBadgeAtIndex(index, 1);
					
					 
				}

			}
		});

		return convertView;
	}

	public static class ViewHolder {
		TextView txt_pro_name;
		TextView txt_pro_description;
		ImageView iv_product;
		ProgressBar progressBar;
		TextView txt_price;
		ImageButton btn_add_tocart;
	}

}
